package com.carl.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.carl.common.dto.es.SkuESModel;
import com.carl.mall.search.config.MallElasticSearchConfiguration;
import com.carl.mall.search.constant.ESConstant;
import com.carl.mall.search.service.ElasticSaveService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 实现上架数据到es的操作
     * @param skuESModels
     * @return
     */
    @Override
    public Boolean productStatusUp(List<SkuESModel> skuESModels) throws IOException {
        if (log.isInfoEnabled()){
            log.info("ElasticSaveServiceImpl.productStatusUp.skuESModels:{}", JSON.toJSONString(skuESModels));
        }
        //创建索引库 -> 创建product映射
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModels) {
            //绑定索引库
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            //设置skuId
            indexRequest.id(skuESModel.getSkuId().toString());
            //设置文档
            ObjectMapper objectMapper = new ObjectMapper();
            //将对象转换成json字符串
            String json = objectMapper.writeValueAsString(skuESModel);
            indexRequest.source(json, XContentType.JSON);
            //转换后的数据封装到bulk中
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient
                .bulk(bulkRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
        //需要取反 原本bulkResponse.hasFailures()有错误是true
        return !bulkResponse.hasFailures();
    }















}
